



//
//  TempViewController.m
//  OC注入JS
//
//  Created by YYY on 2018/1/6.
//  Copyright © 2018年 YYY. All rights reserved.
//

#import "TempViewController.h"
#import <WebKit/WebKit.h>

@interface TempViewController () <WKNavigationDelegate>

@property (nonatomic,strong)WKWebView *webView;

@property(nonatomic,strong)NSMutableArray *imagesArray;

@end

@implementation TempViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    
    //加载本地html
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [self.webView loadRequest:request1];
}

- (WKWebView *)webView
{
    if (_webView == nil)
    {
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _webView.navigationDelegate = self;
        //_webView.UIDelegate = self;
        _webView.scrollView.scrollsToTop = NO;
        _webView.backgroundColor = [UIColor whiteColor];
    }
    return _webView;
}
- (NSMutableArray *)imagesArray
{
    if (!_imagesArray)
    {
        _imagesArray = [NSMutableArray array];
    }
    return _imagesArray;
}

//在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"在发送请求之前，决定是否跳转 decidePolicyForNavigationAction");
    if ([navigationAction.request.URL.scheme isEqualToString:@"image-preview"])
    {
        NSString *clickImage = navigationAction.request.URL.resourceSpecifier;
        NSInteger selectIndex = 0;
        for (int i=0; i<self.imagesArray.count; i++)
        {
            NSString *imageUrl = self.imagesArray[i];
            if ([imageUrl isEqualToString:clickImage])
            {
                selectIndex = i;
                break;
            }
        }
        NSLog(@"索引：%ld  当前图片：%@",selectIndex,clickImage);
        //展示图片
        [self showImage:clickImage];
        //允许跳转,即加载这个链接对应的内容
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else
    {
        //允许跳转,即加载这个链接对应的内容
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    self.title = self.webView.title;
    //加载完成注入JS事件
    [self.webView evaluateJavaScript:@"\
     function imageClickAction(){\
     var images = document.getElementsByTagName('img');\
     var length = images.length;\
     for(var i=0;i<length;i++){\
     var img = images[i];\
     img.onclick = function(){\
     window.location.href = 'image-preview:' + this.src;\
     }\
     }\
     }\
     " completionHandler:nil];

    //触发方法，给所有图片添加onclick方法
    [self.webView evaluateJavaScript:@"imageClickAction()" completionHandler:nil];
    //获取JS界面的所有图片
    [self getAllImagesFromJS];
}

//获取JS界面的所有图片
- (void)getAllImagesFromJS
{
    [self.webView evaluateJavaScript:@"document.getElementsByTagName('img').length" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@ ",response);
        
        //获取图片对应的src
        for (int i=0; i<[response integerValue]; i++)
        {
            NSString *srcString = [NSString stringWithFormat:@"document.getElementsByTagName('img')[%zi].src",i];
            [self.webView evaluateJavaScript:srcString completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                [self.imagesArray addObject:response];
            }];
        }
    }];
}

//展示图片
- (void)showImage:(NSString *)imageUrl
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
    [self.webView loadRequest:request];
}
@end
